document.getElementById('parseButton').addEventListener('click', parseJSON);

function parseJSON() {
    const jsonInput = document.getElementById('jsonInput').value;
    const resultBody = document.getElementById('resultBody');
    resultBody.innerHTML = '';

    try {
        const data = JSON.parse(jsonInput);
        if (!Array.isArray(data.items)) {
            throw new Error('Invalid JSON structure: missing items array');
        }

        data.items.forEach((item, index) => {
            const row = document.createElement('tr');
            
            // Content column - first line only
            const contentCell = document.createElement('td');
            const content = item.content || '';
            contentCell.textContent = content.split('\n')[0];
            row.appendChild(contentCell);

            // Cover images column
            const coversCell = document.createElement('td');
            const coversDiv = document.createElement('div');
            coversDiv.className = 'cover-images';
            if (item.image_search && Array.isArray(item.image_search.covers)) {
                item.image_search.covers.forEach(coverUrl => {
                    const img = document.createElement('img');
                    img.src = coverUrl;
                    img.alt = 'Cover';
                    coversDiv.appendChild(img);
                });
            }
            coversCell.appendChild(coversDiv);
            row.appendChild(coversCell);

            // Total images count column
            const totalImagesCell = document.createElement('td');
            let totalImages = 0;
            if (Array.isArray(item.images)) {
                item.images.forEach(imageGroup => {
                    if (Array.isArray(imageGroup.items)) {
                        totalImages += imageGroup.items.length;
                    }
                });
            }
            totalImagesCell.textContent = totalImages;
            row.appendChild(totalImagesCell);

            // Download button column
            const actionCell = document.createElement('td');
            const downloadBtn = document.createElement('button');
            downloadBtn.className = 'download-btn';
            downloadBtn.textContent = 'Download Images';
            downloadBtn.onclick = () => downloadImages(item);
            actionCell.appendChild(downloadBtn);
            row.appendChild(actionCell);

            resultBody.appendChild(row);
        });
    } catch (error) {
        alert('Error parsing JSON: ' + error.message);
    }
}

async function downloadImages(item) {
    if (!Array.isArray(item.images)) {
        alert('No images available for download');
        return;
    }

    const originalUrls = [];
    item.images.forEach(imageGroup => {
        if (Array.isArray(imageGroup.items)) {
            imageGroup.items.forEach(img => {
                if (img.original) {
                    originalUrls.push(img.original);
                }
            });
        }
    });

    if (originalUrls.length === 0) {
        alert('No original images found for download');
        return;
    }

    // Create text content with Node.js command
    const command = `node download-images.js ${originalUrls.join(' ')}`;
    
    // Create a text file with the command
    const blob = new Blob([command], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'download-command.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    alert('下载命令已保存到 download-command.txt\n请在命令行中运行该命令来下载图片。');
}

function getFileExtension(url) {
    const extension = url.split('.').pop().toLowerCase();
    return ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(extension) ? extension : 'jpg';
}
